package cn.sciento.export;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

public class ExportFutureManager {
    private Map<String, Future> futureMap = new ConcurrentHashMap<>();

    public List<String> getAllKeys() {
        return (List<String>) this.futureMap.entrySet()
                .stream()
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }

    public Future get(String uuid) {
        return this.futureMap.get(uuid);
    }

    public Future get(UUID uuid) {
        return get(uuid.toString());
    }

    public void put(UUID uuid, Future future) {
        this.futureMap.put(uuid.toString(), future);
    }

    public void remove(UUID uuid) {
        remove(uuid.toString());
    }

    public void remove(String uuid) {
        this.futureMap.remove(uuid);
    }

    public boolean cancel(String uuid) {
        Future future = this.futureMap.get(uuid);
        if (future == null)
            throw new IllegalArgumentException("未找到该导出任务[" + uuid + "]");
        if (future.isCancelled()) {
            this.futureMap.remove(uuid);
            return true;
        }
        return (future.cancel(true) && this.futureMap.remove(uuid) == null);
    }
}
